﻿#region File Description
//-----------------------------------------------------------------------------
// WeaponTower.cs
//
// Attack of the Crazy Pixels
// Copyright (c) 2009 VosSoft
//-----------------------------------------------------------------------------
#endregion
#region License
//-----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2009 VosSoft
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
#endregion

namespace Attack_of_the_Crazy_Pixels
{
    /// <summary>
    /// Defines a WeaponTower.
    /// </summary>
    public sealed class WeaponTower : Tower
    {
        #region Fields

        float damage, fireRate, splashRange;
        float fireRateTime, currentFireRateTime = 0.0f;

        // the current values with upgrades but without any effects from SupportTowers.
        float currentRange;
        float currentDamage;
        float currentFireRate;
        float currentSplashRange;

        Enemy target;
        List<Projectile> projectiles = new List<Projectile>();

        #endregion

        #region Properties

        public float Damage
        {
            get { return damage; }
            set { damage = value; }
        }

        public float FireRate
        {
            get { return fireRate; }
            set
            {
                fireRate = value;
                fireRateTime = 1.0f / fireRate;
            }
        }

        public bool HasSplashDamage
        {
            get { return splashRange > 0.0f; }
        }

        public float SplashRange
        {
            get { return splashRange; }
            set { splashRange = value; }
        }

        public Enemy Target
        {
            get { return target; }
        }

        public List<Projectile> Projectiles
        {
            get { return projectiles; }
        }

        #endregion

        #region Initialization

        /// <summary>
        /// Creates a new WeaponTower.
        /// </summary>
        /// <param name="info">Reference to all Informations for this WeaponTower.</param>
        /// <param name="position">Position of the WeaponTower.</param>
        /// <param name="level">Backreference to the Level.</param>
        public WeaponTower(WeaponTowerInfo info, Vector2 position, Level level)
            : base(info, position, level)
        {
            damage = info.Damage[0];
            FireRate = info.FireRate[0];
            splashRange = info.SplashRange[0];

            currentRange = range;
            currentDamage = damage;
            currentFireRate = fireRate;
            currentSplashRange = splashRange;
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the WeaponTowers Projectiles and detects if an Enemy is hit.
        /// </summary>
        /// <param name="elapsedTime">Time since the last frame (in seconds).</param>
        public override void Update(float elapsedTime)
        {
            currentFireRateTime += elapsedTime;
            if (target != null && currentFireRateTime >= fireRateTime)
            {
                projectiles.Add(new Projectile(((WeaponTowerInfo)Info).ProjectileInfo, Position));
                //level.playSound("Gun_Shot");
                currentFireRateTime = 0.0f;
            }

            if (target == null || (target.Position - Position).Length() > range
                || target != null && target.HitPoints <= 0)
            {
                target = newEnemy();
                projectiles.Clear();
            }
            else
            {
                for (int i = 0; i < projectiles.Count; i++)
                {
                    Vector2 projectileToTarget = target.Position - projectiles[i].Position;
                    projectiles[i].Update(elapsedTime, projectileToTarget);

                    // if true, the Projectile hits the target.
                    if (projectileToTarget.Length() < target.Scale.X)
                    {
                        if (HasSplashDamage)
                        {
                            // apply the splash damage to all Enemies in splash range.
                            for (int j = 0; j < level.Enemies.Count; j++)
                            {
                                if (level.Enemies[j] != target) // don't hit the actual target with the splash damage
                                {
                                    float enemyDistance = (level.Enemies[j].Position - target.Position).Length();
                                    if (enemyDistance <= splashRange)
                                    {
                                        float splashDamageFactor = 1.0f - enemyDistance / splashRange;
                                        level.Enemies[j].Hit(damage * splashDamageFactor);
                                    }
                                }
                            }
                        }

                        // hit the target with the damage of this Tower.
                        if (target.Hit(damage)) // target is dead!
                        {
                            target = null;

                            // just return now, all the remaining projectiles
                            // will be removed in the next frame!
                            return;
                        }

                        // remove the Projectile
                        projectiles.RemoveAt(i);
                    }
                }
                Rotation = Calc.VectorToRadians(Position - target.Position);
            }

            // reset these attrributes, because SupportTowers in range
            // may multiply their support value to them.
            range = currentRange;
            damage = currentDamage;
            FireRate = currentFireRate;
            splashRange = currentSplashRange;
        }

        /// <summary>
        /// Returns the next Enemy in fire range (if any).
        /// </summary>
        /// <returns>The first Enemy in fire range, otherwise null.</returns>
        private Enemy newEnemy()
        {
            foreach (Enemy enemy in level.Enemies)
            {
                if ((enemy.Position - Position).Length() <= Range)
                {
                    return enemy;
                }
            }
            return null;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Upgrades the WeaponTower.
        /// </summary>
        public override void Upgrade()
        {
            if (upgradeLevel < Info.MaxUpgradeLevel)
            {
                base.Upgrade();

                currentRange = Info.Range[upgradeLevel];
                currentDamage = ((WeaponTowerInfo)Info).Damage[upgradeLevel];
                currentFireRate = ((WeaponTowerInfo)Info).FireRate[upgradeLevel];
                currentSplashRange = ((WeaponTowerInfo)Info).SplashRange[upgradeLevel];
            }
        }

        public override string ToString()
        {
            return base.ToString() + ", " + String.Format("Damage = {0}, FireRate = {1}, SplashRange = {2}, ProjectileCount = {3}",
                damage, fireRate, splashRange, projectiles.Count);
        }

        #endregion
    }
}
